package cn.stylefeng.guns.modular.weixin.handler;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.log.Log;
import cn.stylefeng.guns.modular.recy.entity.Bins;
import cn.stylefeng.guns.modular.recy.entity.OrderForm;
import cn.stylefeng.guns.modular.recy.entity.WechatUser;
import cn.stylefeng.guns.modular.recy.service.BinsService;
import cn.stylefeng.guns.modular.recy.service.OrderFormService;
import cn.stylefeng.guns.modular.recy.utils.DictUtils;
import cn.stylefeng.guns.modular.recy.utils.UserNoCreator;
import cn.stylefeng.guns.modular.weixin.builder.TextBuilder;
import cn.stylefeng.guns.modular.weixin.utils.WxUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.*;
import java.util.*;
import me.chanjar.weixin.mp.api.*;
import me.chanjar.weixin.common.session.*;
import me.chanjar.weixin.mp.bean.message.*;
import cn.hutool.core.lang.*;
import me.chanjar.weixin.common.error.*;

@Component
public class ScanHandler extends AbstractHandler
{
    @Autowired
    private BinsService binsService;
    @Autowired
    private OrderFormService orderFormService;
    @Autowired
    private UserNoCreator userNoCreator;
    public WxMpXmlOutMessage handle(final WxMpXmlMessage wxMpXmlMessage, final Map<String, Object> map, final WxMpService wxMpService, final WxSessionManager wxSessionManager) throws WxErrorException {
        Console.print(map+"\n");
        System.out.println("扫描关注ticket:" + wxMpXmlMessage.getTicket());
        String eventKey = wxMpXmlMessage.getEventKey();
        Console.print("eventKey:"+eventKey+"\n");
        String msg = "";
        if (StringUtils.isNotBlank(eventKey) && StringUtils.isNumeric(eventKey)) {
            Long binsId = Convert.toLong(eventKey,-1l);
            if(!binsId.equals(-1l)) {
                Bins bins = binsService.getById(binsId);
                if(bins!=null){
                    final WxMpUser userWxInfo = wxMpService.getUserService().userInfo(wxMpXmlMessage.getFromUser());
                    if (userWxInfo != null) {
                        WechatUser user = this.wechatUserService.findByOpenId(userWxInfo.getOpenId());
                        if (user == null) {
                            user = new WechatUser();
                            user.setOpenId(userWxInfo.getOpenId());
                            user.setAvatarUrl(userWxInfo.getHeadImgUrl());
                            user.setWechatNickName(userWxInfo.getNickname());
                            user.setUserNo(Long.valueOf(this.userNoCreator.incrementAndGet()));
                            user.setStatus(DictUtils.me().id("wxuser_status::common"));
                            user.setCreateTime(new Date());
                            final String mpCode = WxUtils.getMpCode(wxMpXmlMessage.getToUser());
                            if (!StringUtils.isAnyBlank(new CharSequence[]{mpCode})) {
                                user.setMpCode(mpCode);
                            }
                            this.wechatUserService.save(user);
                        }
                        if(user!=null){
                            if(StringUtils.isBlank(user.getPhone()) && StringUtils.isBlank(user.getRemark())) {
                                msg += "<a href=\"" + wxMpService.oauth2buildAuthorizationUrl(
                                        String.format(WxUtils.MP_DOMAIN + "/app/completeUserInfo"),
                                        WxConsts.OAuth2Scope.SNSAPI_USERINFO, null) + "\">您的个人信息尚未完善，请点击前往完善。</a>";
                            }
                        }
                        QueryWrapper<OrderForm> queryWrapper = new QueryWrapper<>();
                        queryWrapper.lambda().eq(OrderForm::getBinsId,binsId).eq(OrderForm::getUserId,user.getId()).eq(OrderForm::getState, DictUtils.me().id("order_form_state::create"));
                        List<OrderForm> orderFormList = this.orderFormService.list(queryWrapper);
                        if(orderFormList.size()<=0) {

                            OrderForm orderForm = OrderForm.builder().userId(user.getId()).binsId(binsId).createTime(new DateTime()).state(DictUtils.me().id("order_form_state::create")).build();
                            orderForm.insert();
                        }else{
                            System.out.println("存在未完成订单");
                        }
                    }
                    }



            }
        }
        System.out.println("扫描推送："+msg);
        if(StringUtils.isNotBlank(msg)){
            return new TextBuilder().build(msg,wxMpXmlMessage,wxMpService);
        }
        return null;
    }
}
